package com.example.musicaiap.mvi.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

/**
 * MVI架构的基础ViewModel
 * 
 * @param S 表示UI状态的类型，必须实现UiState接口
 * @param I 表示用户意图的类型，必须实现UiIntent接口
 * @param E 表示UI效应的类型，必须实现UiEffect接口
 */
abstract class MviViewModel<S : UiState, I : UiIntent, E : UiEffect> : ViewModel() {
    
    // 当前UI状态
    private val _uiState: MutableStateFlow<S> by lazy { MutableStateFlow(createInitialState()) }
    val uiState: StateFlow<S> = _uiState.asStateFlow()
    
    // 当前状态的快捷访问方式
    protected val currentState: S get() = uiState.value
    
    // 单向效应通道
    private val _uiEffect = Channel<E>()
    val uiEffect = _uiEffect.receiveAsFlow()
    
    /**
     * 创建初始UI状态
     */
    abstract fun createInitialState(): S
    
    /**
     * 处理用户意图
     */
    abstract fun handleIntent(intent: I)
    
    /**
     * 更新UI状态
     */
    protected fun setState(reduce: S.() -> S) {
        val newState = currentState.reduce()
        _uiState.value = newState
    }
    
    /**
     * 发送一次性UI效应
     */
    protected fun sendEffect(effect: E) {
        viewModelScope.launch {
            _uiEffect.send(effect)
        }
    }
    
    /**
     * 发送意图到ViewModel
     */
    fun sendIntent(intent: I) {
        handleIntent(intent)
    }
} 